#!/usr/bin/env python
# encoding: utf-8
"""
Builds kml from latest Oil Reporter data.  Improves on formatting of kml offered by 
Oil Reporter
"""

import sys
import os
import httplib
import json
from xml.sax import saxutils
from boto.s3 import Connection
from optparse import OptionParser
from datetime import datetime

REPORTS_URL = "/reports.json"
KEY = 'c2ff079be0136d34793289e625d7c49abdfc2c4e'

help_message = '''
The help message goes here.
'''

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def get_records():
    records = []
    page = 0
    conn = httplib.HTTPConnection("oilreporter.org")
    content = []
    while len(content) > 0 or page is 0:
        page = page + 1
        url = "%s?api_key=%s&page=%s" % (REPORTS_URL, KEY, page)
        req = conn.request("GET", url)
        r1 = conn.getresponse()
        if r1.status is 200:
            content = json.loads(r1.read())
            records.extend(content)
        else:
            print "epic fail fetching records"
            return
    return records

def description(r):
    
    d = """
        <table>
        <tr>
        <td width="300">
        <h3><a href="http://oilreporter.org">Oil Reporter</a></h3>
        <p><b>Description:</b> %s</p>
        <p><b>Wetlands:</b> %s/10</p>
        <p><b>Oil:</b> %s/10</p>
        <p><b>Wildlife:</b> %s</p>
        <p><b>Created:</b> %s,</p>
    """ % (r['description'],r['oil'],r['wetlands'],
        r['wildlife'],datetime.strptime(r['created_at'], "%Y-%m-%dT%H:%M:%SZ").strftime("%A %B %d, %Y %H:%M"))
    #d = "<p>%s</p>" % (r['description'], )
    if 'media' in r and r['media'] is not None:
        d = d + '<img src="%s">' % (r['media']['medium'])
    d = d + """    </td>
        </tr>
        </table>
    """
    return """<![CDATA[%s]]>""" % (d, )

def placemarks(records):
    placemarks = []
    for r in records:               
        placemarks.append("""
            <Placemark>
              <styleUrl>#msn_oildrop0</styleUrl>
              <name>Oil Reporter</name>
              <description>%s</description>
              <Point>
                <coordinates>%s,%s,0</coordinates>
              </Point>
              <TimeStamp>
                <when>%s</when>
              </TimeStamp>
            </Placemark>
        """ % (description(r), r['longitude'], 
            r['latitude'], r["created_at"]))
    return "\n".join(placemarks)

def percent_cb(complete, total):
    '''
    Simple progress indicator for transferring files
    '''
    sys.stdout.write('.')
    sys.stdout.flush()

def get_date_range(records):
    begin = None
    end = None
    for r in records:
        dt = datetime.strptime(r['created_at'], "%Y-%m-%dT%H:%M:%SZ")
        if begin is None or dt < begin:
            begin = dt
        if end is None or dt > end:
            end = dt
    return begin, end
            

def create_kml():
    records = get_records()
    begin, end = get_date_range(records)
    # print "\n".join(placemarks)
    kml = """<?xml version="1.0" encoding="UTF-8"?>
        <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
            <Document>
            	<LookAt>
            		<gx:TimeSpan>
            			<begin>%s</begin>
            			<end>%s</end>
            		</gx:TimeSpan>
            		<longitude>-86.5087528807807</longitude>
            		<latitude>28.76558605246543</latitude>
            		<altitude>0</altitude>
            		<range>1420274.687072554</range>
            		<tilt>0</tilt>
            		<heading>1.692316236596836</heading>
            		<altitudeMode>relativeToGround</altitudeMode>
            		<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
            	</LookAt>
                <name>Oil Reporter Reports</name>
                <open>1</open>
                <visibility>1</visibility>
            	<Style id="sh_oildrop0">
            		<IconStyle>
            			<scale>1.2</scale>
            			<Icon>
            				<href>http://commondatastorage.googleapis.com/kml/icons/oildrop.png</href>
            			</Icon>
            		</IconStyle>
            		<LabelStyle>
            			<color>00ffffff</color>
            		</LabelStyle>
            		<BalloonStyle>
                          <!-- a background color for the balloon -->
                          <text>$[description]</text>
                    </BalloonStyle>
            	</Style>
            	<StyleMap id="msn_oildrop0">
            		<Pair>
            			<key>normal</key>
            			<styleUrl>#sn_oildrop</styleUrl>
            		</Pair>
            		<Pair>
            			<key>highlight</key>
            			<styleUrl>#sh_oildrop0</styleUrl>
            		</Pair>
            	</StyleMap>
            	<Style id="sn_oildrop">
            		<IconStyle>
            			<Icon>
            				<href>http://commondatastorage.googleapis.com/kml/icons/oildrop.png</href>
            			</Icon>
            		</IconStyle>
            		<BalloonStyle>
                          <!-- a background color for the balloon -->
                          <text>$[description]</text>
                    </BalloonStyle>
            		<LabelStyle>
            			<color>00ffffff</color>
            		</LabelStyle>
            	</Style>
                %s
            </Document>
        </kml>
    """ % (begin.strftime("%Y-%m-%dT%H:%M:%SZ"), end.strftime("%Y-%m-%dT%H:%M:%SZ"), placemarks(records), )
    
    return kml
    
def main(argv=None):
    usage = "usage: %prog [--upload]"
    parser = OptionParser(usage)
    parser.add_option("-u", "--upload",
                      action="store_true", dest="upload", default=False,
                      help="upload output to s3 as marinemap-gulfspill/oil_reporter.kml. Otherwise output will be directed to stdout")

    (options, args) = parser.parse_args()
    kml = create_kml()
    from kml import create_kmz
    kmz = create_kmz(kml)
    if options.upload:
        #Push kml up to S3.  Requires boto connection config has been setup on the system
        #If a better way of safely providing the aws keys is available, feel free to chance
        connection = Connection()
        bucket = connection.get_bucket('marinemap-gulfspill')
        from boto.s3.key import Key
        k = Key(bucket)
        k.key = 'oil_reporter.kmz'
        k.set_contents_from_string(kmz, cb=percent_cb, num_cb=10)
        k.set_acl('public-read')
        print "\nFile can be access from http://%s/%s" % (".".join((bucket.name, connection.server_name())), k.key)
    else:
        print kml

if __name__ == "__main__":
    sys.exit(main())
